package com.mrru.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mrru.common.dto.LoginDto;
import com.mrru.common.lang.Result;
import com.mrru.entity.User;
import com.mrru.service.UserService;
import com.mrru.utils.JwtUtils;
import org.apache.juli.logging.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 登录接口开发
 * @className: AccountController
 * @author: 茹某
 * @date: 2022/4/29 14:52
 **/
@RestController
public class AccountController
{
    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;


    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){

        //mybatis-plus 实体对象封装操作类 QueryWrapper 根据 Wrapper，查询一条记录
        //返回数据库中的user对象
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        //判断传进来的参数值是否不为空值，如果为空就抛出异常throw new IllegalArgumentException(msg)
        //不为空代码继续向下执行。
        Assert.notNull(user, "用户不存在");

        System.out.println("密码是====="+SecureUtil.md5(loginDto.getPassword()));
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        // 密码正确就创建jwt ,并放在header中 Authorization 里面
        String jwt = jwtUtils.generateToken(user.getId(),user.getUsername());
        response.setHeader("Authorization", jwt);//和JwtFilter里面从header里取出jwt的字段名保持一致
        response.setHeader("Access-Control-Expose-Headers", "Authorization");


        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map());
    }

    //退出接口
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.succ("退出成功");
    }

}
